<template>
	<view>
		<!-- 消息列表 -->
		<u-card v-for="(message, index) in messageList" :key="index" :showHead="false" :showFoot="false"
			@click="toMessageDetail(message)" :body-style="{ padding: '0' }" full="true" margin="0rpx">
			<view slot="body" class="card-body">
				<u-row v-if="message.id">
					<!-- 头像列 -->
					<u-col span="2">
						<u-avatar :src="message.otherPic" mode="square"></u-avatar>
					</u-col>

					<!-- 用户名和内容列 -->
					<u-col span="6">
						<u-row>
							<text class="username">{{ message.otherUserNickname }}</text>
						</u-row>
						<u-row class="content-row">
							<text class="content">{{ message.lastMessage }}</text>
						</u-row>
					</u-col>

					<!-- 时间列 -->
					<u-col span="4">
						<text class="time">{{ formatMessageTime(message.lastMessageTime) }}</text>
					</u-col>
				</u-row>
			</view>
		</u-card>

		<!-- 加载更多提示 -->
		<u-loadmore :status="loadStatus" v-if="messageList.length > 0" />

		<!-- 空状态提示 -->
		<u-empty mode="message" icon="http://cdn.uviewui.com/uview/empty/message.png"
			v-if="messageList.length === 0 &&!loading">
			<text class="empty-text">暂无消息</text>
		</u-empty>
	</view>
</template>

<script>
	import {
		list
	} from '../../utils/api/modules/message';
	import {
		personalDetailById
	} from '../../utils/api/modules/user';
	import stomp from '../../utils/stomp';

	export default {
		data() {
			return {
				messageList: [], // 消息列表，每条消息包含 otherUserId
				loading: false,
				loadStatus: 'loadmore',
				currentPage: 1,
				pageSize: 10,
				total: 0,
				subscriptions: {} // 存储每个 otherUserId 的订阅 ID
			};
		},
		methods: {
			// 跳转到消息详情
			toMessageDetail(message) {
				const user = uni.getStorageSync('user');
				if (!user) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				
				uni.reLaunch({
					url: `/pages/message/message-detail?id=${message.otherUserId}&otherNickName=${message.otherUserNickname}&otherPic=${message.otherPic}`
				});
			},

			// 格式化消息时间
			formatMessageTime(isoTime) {
				if (!isoTime) return '';

				const messageDate = new Date(isoTime);
				const now = new Date();

				const messageYear = messageDate.getFullYear();
				const messageMonth = messageDate.getMonth() + 1;
				const messageDay = messageDate.getDate();
				const hours = messageDate.getHours().toString().padStart(2, '0');
				const minutes = messageDate.getMinutes().toString().padStart(2, '0');

				const currentYear = now.getFullYear();
				const currentMonth = now.getMonth() + 1;
				const currentDay = now.getDate();

				if (messageYear!== currentYear) {
					return `${messageYear}-${messageMonth.toString().padStart(2, '0')}-${messageDay.toString().padStart(2, '0')}`;
				} else if (messageMonth!== currentMonth || messageDay!== currentDay) {
					return `${messageMonth}月${messageDay}日 ${hours}:${minutes}`;
				} else {
					return `${hours}:${minutes}`;
				}
			},

			// 加载消息列表
			async loadMessages() {
				if (this.loading) return;

				this.loading = true;
				this.loadStatus = 'loading';

				try {
					// 初始化 WebSocket 连接
					stomp.init('http://localhost:1110/ZHLG/ws-chat', () => {
						this.stompConnected = true;
						// 订阅所有已加载聊天的消息
						this.subscribeToMessages();
					}, (error) => {
						console.error('STOMP连接错误:', error);
						this.stompConnected = false;
					});

					// 请求初始消息列表
					const res = await list({
						pageNum: this.currentPage,
						pageSize: this.pageSize,
						userId: uni.getStorageSync('user').id
					});

					let data = res.data || [];
					this.total = res.total || 0;

					if (this.currentPage === 1) {
						this.messageList = data;
					} else {
						this.messageList = [...this.messageList, ...data];
					}

					// 判断是否还有更多数据
					if (data.length < this.pageSize) {
						this.loadStatus = 'nomore';
					} else {
						this.loadStatus = 'loadmore';
					}

					// 订阅新加载的聊天的消息
					this.subscribeToMessages();
				} catch (err) {
					console.error('获取消息列表失败:', err);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},

			// 订阅所有已加载聊天的消息
			subscribeToMessages() {
				if (!this.stompConnected) return;

				// 遍历 messageList，为每个 otherUserId 订阅消息
				this.messageList.forEach(message => {
					const messageId = message.id;

					// 如果已经订阅过，则跳过
					if (this.subscriptions[messageId]) {
						return;
					}
					
					// 订阅该聊天的消息
					const subscriptionId = stomp.subscribe(`/topic/chat/${messageId}`, (message) => {
						console.log("收到聊天框消息: " + JSON.stringify(message))
						this.handleIncomingMessage(message);
					});

					// 存储订阅 ID
					this.subscriptions[messageId] = subscriptionId;
				});
			},

			// 处理接收到的 WebSocket 消息
			handleIncomingMessage(rawMessage) {
				try {
					const message = rawMessage; 
					// 确保消息包含必要的字段
					if (!message.id) {
						console.error('接收到的消息格式不正确:', message);
						return;
					}
					// 查找是否已存在该聊天的记录
					const existingMessageIndex = this.messageList.findIndex(
						m => m.id === message.chatId
					);

					if (existingMessageIndex!== -1) {
						// 更新现有记录
						this.$set(this.messageList, existingMessageIndex, {
							...this.messageList[existingMessageIndex],
							lastMessage: message.content,
							lastMessageTime: message.createTime
						});
					} else {
						// 添加新记录到顶部
						this.messageList.unshift({
							id: message.chatId,
							otherUserId: uni.getStorageSync("user").id == message.senderId? message.receiverId : message.senderId,
							otherUserNickname: message.otherUserNickname || '未知用户',
							otherPic: message.otherPic || '',
							lastMessage: message.lastMessage,
							lastMessageTime: message.lastMessageTime
						});

						// 如果超出 pageSize，移除最后一条
						if (this.messageList.length > this.pageSize) {
							this.messageList.pop();
						}

						// 订阅新聊天的消息
						if (this.stompConnected) {
							const subscriptionId = stomp.subscribe(`/topic/chat/${message.chatId}`, (newMessage) => {
								this.handleIncomingMessage(JSON.parse(newMessage.body));
							});
							this.subscriptions[message.otherUserId] = subscriptionId;
						}
					}
				} catch (error) {
					console.error("解析消息失败:", error);
				}
			},

			// 下拉刷新
			onPullDownRefresh() {
				this.currentPage = 1;
				this.loadMessages().finally(() => {
					uni.stopPullDownRefresh();
				});
			},

			// 上拉加载更多
			onReachBottom() {
				if (this.loadStatus === 'nomore' || this.loading) return;
				this.currentPage++;
				this.loadMessages();
			},

			// 页面卸载时取消所有订阅并断开 WebSocket
			onUnload() {
				this.unsubscribeAll();
				stomp.disconnect();
			},

			// 取消所有订阅
			unsubscribeAll() {
				Object.keys(this.subscriptions).forEach(otherUserId => {
					const subscriptionId = this.subscriptions[otherUserId];
					stomp.unsubscribe(subscriptionId);
				});
				this.subscriptions = {};
			}
		},
		onLoad() {
			this.loadMessages();
		},
		// 启用下拉刷新
		onPullDownRefresh() {
			this.onPullDownRefresh();
		},
		// 启用上拉加载更多
		onReachBottom() {
			this.onReachBottom();
		}
	};
</script>

<style scoped>
	/* 卡片主体样式 */
	.card-body {
		padding: 20rpx;
		width: 100%;
	}

	/* 用户名样式 */
	.username {
		font-weight: bold;
		font-size: 16px;
		margin-bottom: 8px;
		display: block;
		width: 100%;
	}

	/* 内容样式 */
	.content {
		font-size: 14px;
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	/* 内容行样式 */
	.content-row {
		margin-top: 8px;
	}

	/* 时间样式 */
	.time {
		width: 100%;
		text-align: right;
		display: block;
		font-size: 12px;
		padding-top: 4px;
	}

	/* 卡片整体样式调整 */
	.u-card {
		box-shadow: none;
		width: 100%;
	}

	/* 调整列间距 */
	.u-row {
		align-items: center;
		padding: 0 10rpx;
	}

	/* 空状态文本样式 */
	.empty-text {
		font-size: 14px;
		color: #909399;
	}

	/* 全局调整 */
	view {
		box-sizing: border-box;
	}
</style>